import threading
import time
import logging
from datetime import datetime, timedelta
from src.models.models import SystemConfig
from src.services.crawler import crawl_all_active_subscriptions
from src.services.downloader import process_download_queue

# 导入 Flask 的 current_app，虽然直接解决问题用不到，但这是一个好的实践
# from flask import current_app # 暂时不需要，因为我们将直接传递app实例

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 全局变量
scheduler_thread = None
scheduler_running = False
scheduler_lock = threading.Lock()

# 新增一个全局变量来存储 Flask 应用实例
_app_instance = None


def scheduler_worker():
    """定时任务工作线程"""
    global scheduler_running

    logger.info("定时任务启动")

    while scheduler_running:
        # 在每次循环开始时推入应用程序上下文
        # 确保 _app_instance 已经被 init_scheduler 设置
        if _app_instance is None:
            logger.error("Flask 应用实例未设置，定时任务无法运行。")
            time.sleep(60)  # 避免无限循环
            continue

        with _app_instance.app_context():  # <--- 关键修改：在这里推入应用程序上下文
            try:
                # 检查是否仍然启用
                enabled = SystemConfig.get_config('scheduler_enabled', 'false') == 'true'
                if not enabled:
                    logger.info("定时任务已被禁用，停止运行")
                    break

                # 获取爬取间隔
                interval_minutes = int(SystemConfig.get_config('crawl_interval', '60'))  # type: ignore

                logger.info(f"开始执行定时爬取任务，间隔: {interval_minutes}分钟")

                # 执行爬取
                result = crawl_all_active_subscriptions()

                if result['success']:
                    logger.info(f"定时爬取完成: {result['message']}")
                    
                    # 处理下载队列
                    queue_processed = process_download_queue()
                    if queue_processed > 0:
                        logger.info(f"处理了 {queue_processed} 个下载队列任务")
                else:
                    logger.error(f"定时爬取失败: {result['message']}")

                # 等待下次执行
                sleep_seconds = interval_minutes * 60
                # sleep_seconds = interval_minutes
                for _ in range(sleep_seconds):
                    if not scheduler_running:
                        break
                    time.sleep(1)

            except Exception as e:
                logger.error(f"定时任务执行出错: {str(e)}")
                # 出错后等待1分钟再继续
                time.sleep(60)

    logger.info("定时任务已停止")


def start_scheduler():
    """启动定时任务"""
    global scheduler_thread, scheduler_running

    with scheduler_lock:
        if scheduler_running:
            logger.info("定时任务已在运行中")
            return True

        try:
            scheduler_running = True
            scheduler_thread = threading.Thread(target=scheduler_worker, daemon=True)
            scheduler_thread.start()

            logger.info("定时任务已启动")
            return True

        except Exception as e:
            logger.error(f"启动定时任务失败: {str(e)}")
            scheduler_running = False
            return False


def stop_scheduler():
    """停止定时任务"""
    global scheduler_thread, scheduler_running

    with scheduler_lock:
        if not scheduler_running:
            logger.info("定时任务未在运行")
            return True

        try:
            scheduler_running = False

            # 等待线程结束
            if scheduler_thread and scheduler_thread.is_alive():
                scheduler_thread.join(timeout=5)

            scheduler_thread = None

            logger.info("定时任务已停止")
            return True

        except Exception as e:
            logger.error(f"停止定时任务失败: {str(e)}")
            return False


def restart_scheduler():
    """重启定时任务"""
    logger.info("重启定时任务")
    stop_scheduler()
    time.sleep(1)
    return start_scheduler()


def is_scheduler_running():
    """检查定时任务是否在运行"""
    return scheduler_running and scheduler_thread and scheduler_thread.is_alive()


def get_scheduler_status():
    """获取定时任务状态"""
    # 这里也可能需要上下文，但通常在请求处理中调用，所以默认有上下文
    # 如果在其他地方调用，也需要 with _app_instance.app_context():
    return {
        'running': is_scheduler_running(),
        'enabled': SystemConfig.get_config('scheduler_enabled', 'false') == 'true',
        'interval': int(SystemConfig.get_config('crawl_interval', '60'))  # type: ignore
    }


# 修改 init_scheduler 函数，使其接受 Flask 应用实例
def init_scheduler(app_instance):  # <--- 关键修改：接受 app_instance 参数
    """初始化定时任务"""
    global _app_instance
    _app_instance = app_instance  # <--- 关键修改：存储 app_instance
    try:
        # 在这里不需要推入上下文，因为 app.py 调用 init_scheduler 时已经在 app.app_context() 中
        enabled = SystemConfig.get_config('scheduler_enabled', 'false') == 'true'
        if enabled:
            start_scheduler()
            logger.info("应用启动时自动启动定时任务")
    except Exception as e:
        logger.error(f"初始化定时任务失败: {str(e)}")

